package com.tanhua.oss;

import com.aliyun.oss.OSSClient;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class OssTemplate {

    private OssProperties ossProperties;

    public OssTemplate(OssProperties ossProperties) {
        this.ossProperties = ossProperties;
    }

    //上传图片
    public String upload(MultipartFile uploadFile) {
        try {
            //调用oss对象将图片上传
            // 文件新路径
            String fileName = uploadFile.getOriginalFilename();
            String filePath = getFilePath(fileName);
            //创建oss客户端对象
            OSSClient ossClient = new OSSClient(ossProperties.getEndpoint(), ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
            ossClient.putObject(ossProperties.getBucketName(), filePath, new ByteArrayInputStream(uploadFile.getBytes()));
            //返回
            return this.ossProperties.getUrlPrefix() + filePath;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //多文件上传
    public List<String> uploads(MultipartFile[] uploadFiles) {
        List<String> list=new ArrayList<>();
        try {

            for (MultipartFile uploadFile : uploadFiles) {
                // 文件新路径
                String fileName = uploadFile.getOriginalFilename();//原始文件名称t.t1.jpg
                String filePath = getFilePath(fileName);//生成指定的文件存储路径
                //创建oss客户端对象
                OSSClient ossClient = new OSSClient(ossProperties.getEndpoint(), ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());

                // 目录结构：images/2018/12/29/xxxx.jpg
                ossClient.putObject(ossProperties.getBucketName(), filePath, new
                        ByteArrayInputStream(uploadFile.getBytes()));
                list.add(this.ossProperties.getUrlPrefix() + filePath);
            }

            // 上传成功
            return list;
        } catch (Exception e) {
            return null;
        }

    }

    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + System.currentTimeMillis() +
                RandomUtils.nextInt(100, 9999) + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }
}
